import React, { Component } from 'react'
import axios from 'axios'
import PubSub from 'pubsub-js'
import Item from '../Item/Item'
import Dots from '../Dots/Dots'
import './Draw.css'

export default class Draw extends Component {
    state = {
        prizeList: [],  //用于渲染九宫格的奖品信息列表
        prizeId: '',    //抽奖结果的物品ID
        rounds: 0,  //转动圈数
        freeNum: 0,  //剩余免费抽奖次数
        isWin: false,   //是否中奖
        isPlaying: false,   //是否正在抽奖
        isShine: true,  //用于控制灯光闪烁
    }

    componentDidMount() {
        let prizes;
        axios.get('http://localhost:5000/prizes').then(
            res => {
                // console.log(res.data);
                // 获取数据后,为每一项加入isActive属性，并在数组中间插入一个对象，最后得到的prizeList用于渲染出九宫格
                prizes = res.data.prizes.map(item => {
                    item.isActive = false;
                    return item;
                });
                prizes.splice(4, 0, { id: '0xclick', title: '点击抽奖', img: '', isActive: 'false' })
                this.setState({
                    prizeList: prizes,
                    rounds: res.data.rounds,
                    freeNum: res.data.freeNum
                });
            }, err => {
                console.log(err);
            }
        )
    }

    getDrawResult = () => {
        if (this.state.isPlaying) return;  //若isPlaying为true,说明上一次抽奖未结束，对点击不做处理
        axios.get('http://localhost:5000/prize/id').then(
            res => {
                // console.log(res.data);
                this.setState({
                    prizeId: res.data.prizeId,
                    isWin: res.data.isWin,
                    freeNum: res.data.freeNum
                });
                this.start();
            }, err => {
                console.log(err);
            }
        )
    }

    start = () => {
        const { freeNum, prizeList, prizeId, isWin } = this.state;
        if (freeNum < 1) {
            alert('免费抽奖次数已用完~');
            return;
        }
        const prizeIndex = prizeList.findIndex(item => item.id === prizeId); //找到抽奖结果id对应在数组中的索引值
        //将抽奖结果信息发布给Show组件,以展示抽奖结果信息
        const prize = prizeList.find((item, index) => index === prizeIndex);
        prize.isWin = isWin;
        PubSub.publish('prizeInfo', prize);
        // console.log(prize);
        this.setState({ isPlaying: true }, () => this.scroll(prizeIndex));
    }

    scroll = (prizeIndex) => {
        const { prizeList, rounds } = this.state;
        const list = [0, 1, 2, 5, 8, 7, 6, 3];  //按顺时针滚动的转动次序列表
        const total = rounds * 8 + list.indexOf(prizeIndex) + 1;    //计算出滚动总次数
        let num = -1;   //统计滚动次数，初始化为-1
        let time = 0; //滚动速度
        let that = this;
        this.rolling = setTimeout(roll, time);
        this.flicker = setTimeout(this.shine, 500);

        // 控制滚动的函数
        function roll() {
            num++;
            let activeId = list[num % 8];   //计算出滚动到下一次的方块位置对应在奖品信息数组中的下标
            that.setState({  //遍历奖品信息数组，设置相对应的isActive属性
                prizeList: prizeList.map((item, index) => index === activeId ? { ...item, isActive: true } : { ...item, isActive: false }),
            });
            //滚动速度控制，慢速 -> 快速 -> 慢速
            if (num < total) {  //若当前滚动次数小于滚动总次数，则继续延时调用roll函数
                if ((num < 3) || (total - num < 3)) {
                    time = 500;
                    that.rolling = setTimeout(roll, time);
                } else if ((num < 8) || (total - num < 8)) {
                    time = 300;
                    that.rolling = setTimeout(roll, time);
                } else {
                    time = 100;
                    that.rolling = setTimeout(roll, time);
                }
            } else {    //若当前滚动次数大于等于滚动总次数，停止滚动
                that.setState({ isPlaying: false });
                that.props.changeShowPrize();    //展示抽奖结果
                clearTimeout(that.rolling);
                clearTimeout(that.flicker);
            }
        }
    }

    //控制灯光闪烁的函数
    shine = () => {
        this.setState({ isShine: !this.state.isShine });
        this.flicker = setTimeout(this.shine, 500);
    }

    render() {
        const { isPlaying, freeNum, isShine } = this.state;
        const list1 = [1, 2, 3, 4, 5, 6];   //控制灯光亮暗顺序
        const list2 = [6, 5, 4, 3, 2, 1];
        return (
            <div className="tableBox ">
                <span style={{ position: 'absolute', top: '-60px', color: '#faf147' }}>免费抽奖次数：{freeNum}</span>
                <span style={{ position: 'absolute', top: '-60px', right: '0', color: '#faf147' }}>免费抽奖</span>
                <Dots isShine={isShine} list={list1} classCtrl={'h_order'}></Dots>
                <Dots isShine={isShine} list={list2} classCtrl={'v_order'}></Dots>
                <Dots isShine={isShine} list={list2} classCtrl={'h_order toBottom'}></Dots>
                <Dots isShine={isShine} list={list1} classCtrl={'v_order toRight'}></Dots>
                <div className="turntable">
                    {
                        this.state.prizeList.map((item, index) => {
                            return <Item key={item.id} {...item} index={index} isPlaying={isPlaying} start={this.getDrawResult} />
                        })
                    }
                </div>
            </div>
        )
    }
}